from test_queue import RedisQueue, MysqlDb
import time
import threading

# 第一步------查询审批人数量，id

# 实例化

mydb = MysqlDb()

# exit()

rq = RedisQueue('rq')

lock = threading.Lock()


# 异步出队
def doout(id):
    while 1:

        uid = rq.get_wait_vip('rq_vip', 1)

        if not uid:
            break
        # 如果我能获取到锁(获取到数据)
        if lock.acquire():
            try:
                # 修改字段   将被审批人分配给审批人

                sql = "update `user` set auid = %s where id = %s" % (id, uid[1])

                print(sql)

                mydb.update(sql)

            except Exception as e:
                print(e, '报错')

            finally:

                # 不管对错都执行,释放锁
                lock.release()


# 执行任务
def dojob_threads():
    # 查询审批人有多少个
    start = time.time()

    res = mydb.read_list("select id from `user` where type = 2 order by rand()")

    # print(res)

    #  直接实例化线程实例

    threads = []
    for i in res:
        t = threading.Thread(target=doout, args=(i['id'],))
        threads.append(t)

    [i.start() for i in threads]
    [i.join() for i in threads]

    print(time.time() - start, '线程执行时间')


# dojob_threads()

# 轮询任务

def loopjob():
    while 1:
        print('执行任务')

        dojob_threads()

        time.sleep(20)


# start = time.time()
### 开启分配
# loopjob()
# print(time.time() - start, '线程执行时间')
#
# doout(4)
# exit()

# 出队

# rq.put_r(1)
# rq.put_vip('rq_vip', timout=None,auid=3)

# print(rq.get_wait_vip('rq_vip'))
# rq.put_r(2)

# print(rq.get_lrange(), 'lrange')

# # 是否存在数据  1存在  0不存在数据
# print(rq.exist())
#
# print(rq.get_wait())

